module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const ObjectId = Schema.Types.ObjectId;
  /**
   * @ label data schema
   */
  let LabelSchema = new Schema({
    name: String,
    articles: [{ type: ObjectId, ref: 'Article' }],
    default: { type: Number, default: 0},
    date: { type: Number, default: Date.now }
  }, {usePushEach: true});

  LabelSchema.statics = {
    saveLabel(data) {
      return data.save();
    },
    del({id}) {
      return this.remove({ _id: id }).exec();
    },
    findAll: function(cb) {
      return this.find({})
        .populate('articles')
        .populate('author', {"_id":0,"name":1})
        .exec(cb);
    },
    findById: function(id, cb) {
      return this.findOne({ _id: id }).exec(cb);
    },
    findByName: function(name, cb) {
      return this.findOne({ name: name }).exec(cb);
    },
    findByDefault: function(cb) {
      return this.findOne({ default: 1}).exec(cb);
    },
    addArticle(params) {
      return this.findByIdAndUpdate({_id: params.label_id}, {$push: {articles: params.article_id}}).exec();
    },
    delArticle({lid, aid}) {
      return this.findByIdAndUpdate({_id: lid}, {$pull: {articles: aid}}).exec();
    }
  };

  return mongoose.model('Label', LabelSchema);
}